<template>
  <el-dialog title="分配数据权限" v-model="visible" class="dialog-sm" append-to-body @close="visible = false">
    <el-form ref="formRef" :model="form" label-width="80px" v-loading="loading">
      <el-form-item label="角色名称">
        <el-input v-model="rowData.name" disabled />
      </el-form-item>
      <el-form-item label="权限字符">
        <el-input v-model="rowData.role_key" disabled />
      </el-form-item>
      <el-form-item label="权限范围" prop="data_scope">
        <el-select v-model="form.data_scope" @change="dataScopeChange">
          <el-option v-for="item in scopeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据权限" v-show="form.data_scope === scopeCustom">
        <el-checkbox v-model="deptExpand" @change="handleTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptNodeAll" @change="handleTreeNodeAll">全选/全不选</el-checkbox>
        <el-checkbox v-model="deptCheckStrictly">父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="treeRef"
          node-key="id"
          :check-strictly="!deptCheckStrictly"
          empty-text="加载中，请稍候"
          :props="{ label: 'name', children: 'children' }" />
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button class="medium" type="primary" :loading="submitting" :disabled="loading" @click="handleSubmit"
        >确 定</el-button
      >
      <el-button class="medium" @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script setup name="DataScope">
  import { infoRoleApi, saveDataScopeApi } from '@/api/system/role'
  import { selectDeptApi } from '@/api/system/dept'
  import { dataScopeOptions } from './script'

  const props = defineProps({ id: Number | String })
  const visible = defineModel()
  const { proxy } = getCurrentInstance()

  const form = ref({ data_scope: undefined, dept_ids: [] })
  const scopeOptions = ref(dataScopeOptions)
  const scopeCustom = ref(8)
  const deptCheckStrictly = ref(true)
  const treeRef = useTemplateRef('treeRef')

  // 初始操作
  const loading = ref(false)
  onMounted(async () => {
    loading.value = true
    form.value.id = props.id || undefined
    if (!form.value.id) {
      proxy.$modal.msgError('参数错误')
      visible.value = false
      return
    }
    await getRowData()
    await getDeptOptions()
    loading.value = false
  })

  // 获取信息
  const rowData = ref({})
  async function getRowData() {
    try {
      const { info } = await infoRoleApi(form.value.id)
      rowData.value = info
      form.value = proxy.dataToForm(form.value, info)
    } catch (error) {
      visible.value = false
    }
  }

  // 获取部门树列表
  const deptOptions = ref([])
  async function getDeptOptions() {
    try {
      const { list } = await selectDeptApi()
      deptOptions.value = proxy.listToTree(list)
      nextTick(() => {
        form.value.dept_ids.map(id => {
          treeRef.value.setChecked(id, true, false)
        })
      })
    } catch (e) {}
  }

  // 提交按钮
  const emit = defineEmits(['submit'])
  const submitting = ref(false)
  async function handleSubmit() {
    if (submitting.value) return
    submitting.value = true
    form.value.dept_ids = getAllCheckedKeys()
    try {
      await proxy.$modal.confirm('确定提交表单数据？')
      await saveDataScopeApi(form.value)
      emit('submit')
      proxy.$modal.msgSuccess('操作成功')
      visible.value = false
    } catch (e) {
      submitting.value = false
    }
  }

  // 所有菜单选中节点数据
  function getAllCheckedKeys() {
    let checkedKeys = treeRef.value.getCheckedKeys() // 目前被选中的菜单节点
    let halfCheckedKeys = treeRef.value.getHalfCheckedKeys() // 半选中的菜单节点
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
    return checkedKeys
  }

  // 选择角色权限范围触发
  function dataScopeChange(value) {
    if (value !== scopeCustom.value) treeRef.value.setCheckedKeys([])
  }

  // 树权限（展开/折叠）
  const deptExpand = ref(false)
  function handleTreeExpand(checked) {
    let treeList = deptOptions.value
    for (let i = 0; i < treeList.length; i++) {
      treeRef.value.store.nodesMap[treeList[i].id].expanded = checked
    }
  }

  // 树权限（全选/全不选）
  const deptNodeAll = ref(false)
  function handleTreeNodeAll(checked) {
    treeRef.value.setCheckedNodes(checked ? deptOptions.value : [])
  }
</script>
